package com.lmxdawn.api.im.service;

import cn.hutool.extra.spring.SpringUtil;
import lombok.var;
import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.util.ChatKit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static org.jim.core.ImConst.*;
import static org.jim.core.packets.Command.COMMAND_CHAT_REQ;

public class ImUtil {

    private static final Logger log = LoggerFactory.getLogger(ImUtil.class);

    public static void moveUserToFirst(String groupId){
        moveUser(groupId, 0);
    }

    public static void sendToGroup(String groupId, ChatBody chatBody){
        RespBody respBody = new RespBody(COMMAND_CHAT_REQ, chatBody);
        ImPacket imPacket = new ImPacket(COMMAND_CHAT_REQ, respBody.toByte());
        JimServerAPI.sendToGroup(groupId, imPacket);
        pushGroupMessages(PUSH, STORE, chatBody, true);
    }


    /**
     * 推送持久化群组消息
     * @param pushTable
     * @param storeTable
     * @param chatBody
     */
    private static void pushGroupMessages(String pushTable, String storeTable , ChatBody chatBody, boolean isStore){
        ImServerConfig imServerConfig = (ImServerConfig)JimServerAPI.imConfig;
        MessageHelper messageHelper = imServerConfig.getMessageHelper();
        String group_id = chatBody.getGroupId();
        //先将群消息持久化到存储Timeline;
        messageHelper.writeMessage(storeTable, GROUP+":"+group_id, chatBody);
        List<String> userIds = messageHelper.getGroupUsers(group_id);
        //通过写扩散模式将群消息同步到所有的群成员
        for(String userId : userIds){
            boolean isOnline = false;
            if(isStore && ImServerConfig.ON.equals(imServerConfig.getIsCluster())){
                isOnline = messageHelper.isOnline(userId);
            }else{
                isOnline = ChatKit.isOnline(userId, isStore);
            }
            if(!isOnline){
                messageHelper.writeMessage(pushTable, GROUP+":"+group_id+":"+userId, chatBody);
            }
        }
    }


    public static void moveUser(String groupId, int index){
        log.info("groupId:{},index:{}", groupId, index);
        if (groupId.contains("-notify")){
            return ;
        }
        RedissonClient redissonClient =  SpringUtil.getBean(RedissonClient.class);
        var jimOnlineUser = redissonClient.getList("JIM_ONLINE_USER");
        index = index == -1 ? (jimOnlineUser.size() - 1) : index;
        RLock lock = redissonClient.getLock("JIM_ONLINE_USER_LOCK");
        try {
            if (lock.tryLock(3, TimeUnit.SECONDS)){
                if (jimOnlineUser.contains(groupId)){
                    jimOnlineUser.remove(groupId) ;
                }
                jimOnlineUser.add(index, groupId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
